/**
 * AI助手Hook
 * 提供AI功能的React Hook封装
 */

import { useState, useRef, useCallback, useEffect } from 'react'
import { AIService } from '../../services/ai/aiService'
import { AIError, AIErrorCode, getAIConfig } from '../../services/ai'

export function useAIAssistant() {
  const [isGenerating, setIsGenerating] = useState(false)
  const [error, setError] = useState<AIError | null>(null)
  const aiServiceRef = useRef<AIService | null>(null)

  // 初始化AI服务
  useEffect(() => {
    const config = getAIConfig()
    if (config && config.apiKey) {
      aiServiceRef.current = new AIService({
        openaiApiKey: config.apiKey,
        baseURL: config.apiBaseUrl,
        model: config.model,
        contextLength: 1000
      })
      console.log('[useAIAssistant] AI服务已初始化', {
        model: config.model,
        baseURL: config.apiBaseUrl || 'https://api.openai.com/v1'
      })
    } else {
      console.log('[useAIAssistant] 未找到API密钥配置')
    }
  }, [])

  /**
   * AI续写
   */
  const continueWriting = useCallback(async (params: {
    fullText: string
    cursorPosition: number
  }) => {
    if (!aiServiceRef.current) {
      const err: AIError = {
        code: AIErrorCode.API_KEY_MISSING,
        message: '请先配置OpenAI API密钥'
      }
      setError(err)
      return null
    }

    setIsGenerating(true)
    setError(null)

    console.log('[useAIAssistant] 开始AI续写', {
      textLength: params.fullText.length,
      cursorPosition: params.cursorPosition
    })

    const result = await aiServiceRef.current.continueWriting(params)

    setIsGenerating(false)

    if (!result.ok) {
      console.error('[useAIAssistant] AI续写失败', result.error)
      setError(result.error)
      return null
    }

    console.log('[useAIAssistant] AI续写成功', {
      generatedLength: result.data.length
    })

    return result.data
  }, [])

  /**
   * 清除错误
   */
  const clearError = useCallback(() => setError(null), [])

  /**
   * 重新加载配置
   */
  const reloadConfig = useCallback(() => {
    const config = getAIConfig()
    if (config && config.apiKey) {
      aiServiceRef.current = new AIService({
        openaiApiKey: config.apiKey,
        baseURL: config.apiBaseUrl,
        model: config.model,
        contextLength: 1000
      })
      console.log('[useAIAssistant] 配置已重新加载', {
        model: config.model,
        baseURL: config.apiBaseUrl || 'https://api.openai.com/v1'
      })
      return true
    }
    return false
  }, [])

  return {
    isGenerating,
    error,
    continueWriting,
    clearError,
    reloadConfig,
    hasConfig: !!aiServiceRef.current
  }
}
